﻿using System.Collections.Generic;
using UnityEngine;

namespace CWM.Skinn
{
    [ExecuteInEditMode]
    [RequireComponent(typeof(Animator))]
    public class BlendshapeController : MonoBehaviour
    {
        [System.Serializable]
        public class ShapeSettings
        {
            [Header("Sliders")]
            [Tooltip("Use min and max for sliders.")]
            public bool unclampShapes = false;

            [Tooltip("min slider value for blend-shapes")]
            public float min = -100f;

            [Tooltip("max slider value for blend-shapes")]
            public float max = 100f;

            [Header("Hidden Shapes")]
            [Tooltip("Hide Blend-shapes that start with this string.")]
            public string hiddenPrefix = "pJCM";
            [Tooltip("Hide Blend-shapes that contain this string.")]
            public string hiddenTag = "";
        }

        [Tooltip("setting for the blend-shape inspector.")]
        public ShapeSettings settings = new ShapeSettings();

        [HideInInspector] public string serachString = "";

        [HideInInspector] public BlendableElements blendableElements = new BlendableElements();

        public void OnEnable() { UpdateBlendableElements(); }

        [ContextMenu("Update Blendshapes")]
        public void UpdateBlendableElements()
        {
            blendableElements = new BlendableElements();
            blendableElements.UpdateAssets(this.gameObject);
            blendableElements.UpdateAllBlendshapes();

            if (!SkinnEx.IsNullOrLessThan(blendableElements.elements, 3))
                blendableElements.elements.Sort(1, blendableElements.elements.Count - 1, new SortShapes());
        }

        private static string PadNumbers(string input)
        {
            return System.Text.RegularExpressions.Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10, '0'));
        }

        private class SortShapes : IComparer<BoneElement>
        {
            int IComparer<BoneElement>.Compare(BoneElement p1, BoneElement p2)
            {
                return PadNumbers(p1.Name).CompareTo(PadNumbers(p2.Name));
                //return p1.Name.CompareTo(p2.Name);
            }
        }

    }
}